﻿using System;
using System.IO;
using System.Text;
using System.Xml;

//自定义命名空间
using DreamCube.Foundation.WMI;
using DreamCube.Foundation.Validate;
using DreamCube.Foundation.Security;
using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.Framework.Utilities.Authorization
{
    /// <summary>
    /// 授权的帮助类
    /// </summary>
    public static class AuthoriseHelper
    {
        /// <summary>
        /// 当前程序运行的目录
        /// </summary>
        private static String appPath = AppDomain.CurrentDomain.BaseDirectory;

        /// <summary>
        /// 验证授权
        /// </summary>
        /// <param name="securityObj">执行的安全加密算法</param>
        /// <returns></returns>
        public static AuthorizeResult Authorize(ISecurity securityObj)
        {
            String data1FileFullName = String.Empty;
            String data0FileFullName = GetData0FileName();
            AuthoriseBasic authorise =
                        AuthoriseFactory.CreateAuthorise(AuthoriseType.IntervalWithHardware, securityObj);
            if (String.IsNullOrEmpty(data0FileFullName))
            {
                authorise.CreateData0FileData(Path.Combine(appPath, authorise.CreateFileNameWithoutExtensionName() + ".dat0"));
                return new AuthorizeResult(false, Properties.Resources.MsgCreateData0);
            }
            data1FileFullName = MyString.LeftOfLast(data0FileFullName, ".") + ".dat1";
            if (!File.Exists(data1FileFullName))
                return new AuthorizeResult(false, Properties.Resources.MsgCreateData0);
            return authorise.Authorise(data1FileFullName);
        }

        #region "私有辅助方法"

        /// <summary>
        /// 判断是否有Data1文件
        /// </summary>
        /// <returns></returns>
        private static String GetData1FileName()
        {
            String[] files = null;
            if (MyIO.TryGetFiles(appPath, out files, "*.dat1", SearchOption.TopDirectoryOnly))
            {
                for (Int32 i = 0; i < files.Length; i++)
                {
                    if (ValidateHelper.Validate("IsData0FileName", files[i]))
                        return files[i];
                }
            }
            return null;
        }

        /// <summary>
        /// 判断是否有Data0文件
        /// </summary>
        /// <returns></returns>
        private static String GetData0FileName()
        {
            String[] files = null;
            if (MyIO.TryGetFiles(appPath, out files, "*.dat0", SearchOption.TopDirectoryOnly))
            {
                for (Int32 i = 0; i < files.Length; i++)
                {
                    if (ValidateHelper.Validate("IsData0FileName", files[i]))
                        return files[i];
                }
            }
            return null;
        }

        #endregion
    }
}
